package com.itheima.youdianda.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.youdianda.common.Result;
import com.itheima.youdianda.domain.SysMenu;
import com.itheima.youdianda.domain.SysRole;
import com.itheima.youdianda.domain.SysRoleMenu;
import com.itheima.youdianda.domain.SysUser;
import com.itheima.youdianda.dto.SysUserDto;
import com.itheima.youdianda.service.SysDictService;
import com.itheima.youdianda.service.SysRoleMenuService;
import com.itheima.youdianda.service.SysRoleService;
import com.itheima.youdianda.service.SysUserService;
import com.itheima.youdianda.mapper.SysUserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author YUAN
 * @description 针对表【sys_user(用户表)】的数据库操作Service实现
 * @createDate 2022-09-06 18:36:39
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser>
        implements SysUserService {

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysRoleMenuService sysRoleMenuService;

    @Autowired
    private SysDictService sysDictService;

    @Autowired
    private SysRoleService roleService;
    @Override
    public Map<String, Object> getProfile(String id) {
        Map<String, Object> map = new HashMap<>();
        SysUserDto userInfo = baseMapper.getUserInfo(id);
        List<String> roleIds = Arrays.stream(userInfo.getRoleId()
                .replace("[", "")
                .replace("]", "")
                .replace("\"", "")
                .split(",")).collect(Collectors.toList());
        userInfo.setRole_id(roleIds);
        LambdaQueryWrapper<SysRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(SysRole::getId, roleIds);
        userInfo.setRoleName(sysRoleService.list(queryWrapper).stream().map(SysRole::getName).collect(Collectors.toList()));
        map.put("userInfo", userInfo);
        List<SysMenu> roleMenus = sysRoleMenuService.getRoleMenu(roleIds).stream().filter(r -> StringUtils.isNotBlank(r.getPath())).collect(Collectors.toList());
        map.put("menuList", roleMenus);
        Map<String, List<String>> dictMap = new HashMap<>();
        sysDictService.list().forEach(d -> {
            if (dictMap.containsKey(d.getType())) {
                dictMap.get(d.getType()).add(d.getLabel());
            } else {
                List<String> temp = new ArrayList<>();
                temp.add(d.getLabel());
                dictMap.put(d.getType(), temp);
            }
        });
        map.put("dictList", dictMap);
        map.put("btnList", new String[]{"*"});
        return map;
    }

    /**
     * 添加
     * @param sysUserDto
     */
    @Override
    public void saveWithDto(SysUserDto sysUserDto) {
        getUserDto(sysUserDto);
        sysUserDto.setPassword(DigestUtils.md5DigestAsHex(sysUserDto.getPassword().getBytes()));

        save(sysUserDto);
    }

    /**
     * 修改
     * @param sysUserDto
     */
    @Override
    public void updateWithDto(SysUserDto sysUserDto) {
        getUserDto(sysUserDto);
        if (sysUserDto.getPassword() != null) {
            sysUserDto.setPassword(DigestUtils.md5DigestAsHex(sysUserDto.getPassword().getBytes()));
        }
        this.updateById(sysUserDto);
    }


    /**
     * 查询管理员with角色name
     *
     * @param login_name
     * @param status
     * @param phone
     * @param page
     * @param limit
     */
    public Page<SysUserDto> pageWithDto(String login_name, String status, String phone, Integer page, Integer limit){
        Page<SysUser> userPage = new Page<>(page, limit);
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.isNotBlank(login_name), SysUser::getName, login_name)
                .eq(StringUtils.isNotBlank(status), SysUser::getStatus, status)
                .like(StringUtils.isNotBlank(phone), SysUser::getPhone, phone);

        this.page(userPage, wrapper);

        Page<SysUserDto> userDtoPage = new Page<>();
        BeanUtils.copyProperties(userPage, userDtoPage, "records");

        List<SysUserDto> sysUserInfoList = userPage.getRecords().stream().map(user -> {
            SysUserDto sysUserInfo = new SysUserDto();
            BeanUtils.copyProperties(user, sysUserInfo);

            List<String> roleIdList = getStringRoleIds(user);
            sysUserInfo.setRole_id(roleIdList);

            //查询用户角色名称集合: roleNameList
            List<String> roleNameList = roleService.roleNameList(roleIdList);
            sysUserInfo.setRoleName(roleNameList);
            return sysUserInfo;
        }).collect(Collectors.toList());
        userDtoPage.setRecords(sysUserInfoList);
        return userDtoPage;
    }

    /**
     * 管理员详情
     *
     * @param id
     * @return
     */
    @Override
    public SysUserDto getByIdWithRoleId(String id) {
        SysUser user = this.getById(id);
        SysUserDto sysUserDto = new SysUserDto();
        BeanUtils.copyProperties(user, sysUserDto);
        sysUserDto.setRole_id(getStringRoleIds(user));
        return sysUserDto;
    }

    /**
     * 将String转为roleIdList
     *
     * @param user
     * @return
     */
    private List<String> getStringRoleIds(SysUser user) {
        //查询用户角色id集合: roleIdList
        String[] roleIds = user.getRoleId().replace("[", "")
                .replace("]", "")
                .replace("\"", "")
                .split(",");
        List<String> roleIdList = new ArrayList<>();
        Collections.addAll(roleIdList, roleIds);
        return roleIdList;

    }

    /**
     * 将roleIdList转为String
     * @param sysUserDto
     */
    private void getUserDto(SysUserDto sysUserDto) {
        StringBuilder sb = new StringBuilder();
        List<String> roleIdList = sysUserDto.getRole_id();
        sb.append("[");
        for (int i = 0; i < roleIdList.size(); i++) {
            String roleId = roleIdList.get(i);
            sb.append("\"").append(roleId).append("\"").append(i == roleIdList.size() - 1 ? "" : ",");
        }
        sb.append("]");
        sysUserDto.setRoleId(sb.toString());
    }
}




